package com.wang.tx.core;

import java.util.ArrayList;
import java.util.List;

// 将不同事务进行组合
public class CombineTx extends Tx {
    private List<Tx> txList = new ArrayList<>();
    private int executeIndex = 0;

    public CombineTx(List<Tx> txList) {
        if (txList == null) return;
        this.txList = txList;
    }

    @Override
    protected void prepare() throws Throwable {
        for (executeIndex = 0; executeIndex < txList.size(); executeIndex++) {
            txList.get(executeIndex).prepare();
        }
    }

    @Override
    protected boolean execute() throws Throwable {
        for (executeIndex = 0; executeIndex < txList.size(); executeIndex++) {
            if(!txList.get(executeIndex).execute()) return false;
        }
        return true;
    }

    @Override
    protected void commit() {
        for (Tx tx : txList) {
            tx.commit();
        }
    }

    @Override
    protected void rollback() {
        for (int i = executeIndex; i > 0; i--) {
            txList.get(i).rollback();
        }
    }
}
